﻿using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.SharePoint;

namespace System.Modules.Utility
{
    public partial class WebLookup : Form
    {
        public WebLookup(String siteUrl)
        {
            InitializeComponent();
            using (var worker = new BackgroundWorker())
            {
                worker.DoWork += delegate(object s, DoWorkEventArgs e)
                {
                    if (!string.IsNullOrEmpty(siteUrl))
                    {
                        using (var spSite = new SPSite(siteUrl))
                        {
                            e.Result = GetWeb(spSite.RootWeb);
                        }
                    }
                };
                worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs e)
                {
                    if (e.Error == null)
                    {
                        if (e.Result != null)
                        {
                            var web = e.Result as TreeNode;
                            if (web != null)
                            {
                                tvWebs.Nodes.Add(web);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(e.Error.Message);
                    }
                };
                worker.RunWorkerAsync();
            }
        }

        public TreeNode GetWeb(SPWeb web)
        {
            var node = new TreeNode();
            node.Name = web.ServerRelativeUrl;
            node.Text = web.ServerRelativeUrl;
            node.ToolTipText = web.ServerRelativeUrl;
            node.Tag = web;
            node.Collapse();
            if (web.Webs.Count > 0)
            {
                foreach (SPWeb subWeb in web.Webs)
                {
                    node.Nodes.Add(GetWeb(subWeb));
                }
            }
            return node;
        }

        private void TvWebsAfterSelect(object sender, TreeViewEventArgs e)
        {
            var tv = sender as TreeView;
            var form = Owner as MainForm;
            if (tv != null && form != null)
            {
                var node = tv.SelectedNode;
                if (node != null)
                {
                    var web = node.Tag as SPWeb;
                    if (web != null)
                    {
                        form.WebUrl = web.ServerRelativeUrl;
                        DialogResult = DialogResult.OK;
                    }
                }
            }
        }
    }
}
